#!/usr/bin/env node

//Routes File

'use strict'

/* MODULE IMPORTS */
const fs = require('fs');
const path = require('path');
const Router = require('koa-router');
const koaBody = require('koa-body')({
    multipart: true,
    formidable: {
        maxFileSize: 200 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
    },
    uploadDir: './upload'
});
//const jimp = require('jimp')

/* IMPORT CUSTOM MODULES */
const User = require('../modules/user');

const router = new Router();

/**
 * The script to process new user registrations.
 *
 * @name Register Script
 * @route {POST} /register
 */
router.post('/file/upload', koaBody, async ctx => {
    try {
        var types = ['avatars', 'item_photo'];

        var fileType = ctx.request.body.fileType;

        if (types.indexOf(fileType) < 0) {
            throw "not support file type";
        }

        const file = ctx.request.files.file; // 上传的文件在ctx.request.files.file
        // 创建可读流
        const reader = fs.createReadStream(file.path);
        // 修改文件的名称
        var myDate = new Date();
        var newFilename = myDate.getTime() + '.' + file.name.split('.')[1];
        
        var uploadDir = path.join(__dirname, '../public/uploads');
        var dir = uploadDir + '/' + fileType;

        var targetPath = dir + `/${newFilename}`;

        if(!fs.existsSync(uploadDir)){
            fs.mkdirSync(uploadDir);
        }
        if(!fs.existsSync(dir)){
            fs.mkdirSync(dir);
        }

        //创建可写流
        const upStream = fs.createWriteStream(targetPath);
        // 可读流通过管道写入可写流
        reader.pipe(upStream);
        //返回保存的路径
        // return ctx.body = { code: 200, data: { url: 'http://' + ctx.headers.host + '/uploads/' + newFilename } };

        return ctx.body = {
                uid: '-1',
                name: newFilename,
                status: 'done',
                url: `/uploads/${fileType}/${newFilename}`
            };
    } catch (err) {
        await ctx.render('error', { message: err.message })
    }
})

module.exports = router;

